//app.js
var moment = require("utils/moment.min.js");
moment.locale('en', {
  longDateFormat: {
    l: "YYYY-MM-DD",
    L: "YYYY-MM-DD HH:mm"
  }
});
App({
  onLaunch: function() {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getUserInfo: function(cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function() {
          wx.getUserInfo({
            success: function(res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  timeFormat: function(str) {
    return moment(str).format('L');
  },
  login: function() {
    wx.login({
      success: e => {
        var _code = e.code; //0810E5Jq0BKqUm1sKoHq0vb9Jq00E5JA
        var that = this;
        wx.request({
          url: this.globalData.ip + '/api/user?code=' + _code,
          method: "POST",
          success: e => {
            // console.log(e);
            if (e.data.code == 200) { //已注册
              this.globalData.ifRegister = true
              this.globalData.token = e.data.data
              // wx.switchTab({
              //   url: '../index/index',
              // })
            }else{
              this.globalData.ifRegister = false;
            }
          }
        })
      }
    })
  },
  register: function() {
    var that = this;
    // console.log(this.globalData.userInfo);
    var nickName = this.globalData.userInfo.nickName;
    var url = this.globalData.userInfo.avatarUrl;
    // console.log("register")
    // console.log(nickName,url);
    wx.login({
      success: e => {
        var that = this;
        wx.request({
          url: this.globalData.ip + '/api/user/register?code=' + e.code + "&nickName=" + nickName + "&url=" + url,
          method: "POST",
          success: e => {
            console.log(e);
            this.login();
            this.globalData.ifRegister = true
          }
        })
      }
    })
  },
  globalData: {
    userInfo: null,
    sysWidth: wx.getSystemInfoSync().windowWidth, //图片宽度
    ip: "http://localhost:8080",
    ifRegister:false,
    token:""
  }
})